package com.yun.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.yun.util.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /*1.将我们自定义的UserRealm交给spring管理*/
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }


    /*2.DefaultWebSecurityManager*/
    @Bean("securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        /*关联UserRealm*/
        securityManager.setRealm(userRealm);
        return securityManager;
    }


    /*3.ShiroFilterFactoryBean*/
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        /*设置安全管理器*/
        bean.setSecurityManager(defaultWebSecurityManager);

        /*添加shiro的内置过滤器 下面是链式表达，所以用link
        * anon 无需认证
        * authc 认证才能访问
        * user 必须有记住我功能才能访问
        * perms 必须对某个资源有权限才能访问
        * relo 拥有某个角色权限才能访问 */
        //设置权限
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/getDoctors","anon");
        filterMap.put("/getPets","authc");
        filterMap.put("/getMedical","authc");
        filterMap.put("/getEvaluate","authc");
        filterMap.put("/watchList","authc");
        filterMap.put("/getMessage","authc");
        filterMap.put("/toConsult","authc");
        //授权
        filterMap.put("/getPets","perms[user:a]");
        filterMap.put("/getMedical","perms[doctor:b]");
        filterMap.put("/getEvaluate","perms[user:a]");
        filterMap.put("/watchList","perms[director:c]");
        filterMap.put("/getMessage","perms[director:c]");
        filterMap.put("/toConsult","perms[director:c]");
        bean.setFilterChainDefinitionMap(filterMap);

        /*设置登录认证请求*/
        bean.setLoginUrl("/Unauthorized");
        /*设置未授权请求*/
        bean.setUnauthorizedUrl("/Unauthorized");
        return bean;
    }

        /*整合shiro和thymeleaf*/
        @Bean
        public ShiroDialect  getShiroDialect(){
               return new ShiroDialect();
        }



}
